package org.example.mynote.service.Impl;

import org.example.mynote.Entity.Note;
import org.example.mynote.Entity.Notebook;
import org.example.mynote.Entity.User;
import org.example.mynote.mapper.FavoriteMapper;
import org.example.mynote.mapper.NoteMapper;
import org.example.mynote.mapper.NotebookMapper;
import org.example.mynote.mapper.UserMapper;
import org.example.mynote.service.FavoriteService;
import org.example.mynote.service.NoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.Optional;

import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.NOT_FOUND;

@Service
public class FavoriteServiceImpl implements FavoriteService {
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private NoteMapper noteMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotebookMapper notebookMapper;

    // 收藏笔记
    public void addFavorite(Long noteId) {
        User currentUser = getCurrentUser();

        Note noteToFavorite = (Note) noteMapper.findById(noteId)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记，ID为" + noteId));

        // ----> 在这一步之后，noteToFavorite 就是一个实实在在的 Note 对象了，不再是 Optional <----

        // 2. 现在可以安全地调用 .getNotebookId()
        Long notebookId = noteToFavorite.getNotebookId();

        // 同样地，使用 .orElseThrow() 来获取 Notebook 对象
        Notebook parentNotebook = (Notebook) notebookMapper.findById(notebookId)
                .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "未找到对应笔记本，ID为" + notebookId));

        // 3. 验证笔记本的 user_id 是否与当前用户的 id 匹配
        if (!parentNotebook.getUserId().equals(currentUser.getId())) {
            throw new ResponseStatusException(FORBIDDEN, "无响应笔记本项目");
        }

        // 2. 检查是否已经收藏过，避免重复插入导致数据库唯一约束报错
        if (favoriteMapper.findByUserIdAndNoteId(currentUser.getId(), noteId).isEmpty()) {
            favoriteMapper.insert(currentUser.getId(), noteId);
        }
    }

    // 取消收藏笔记
    public void removeFavorite(Long noteId) {
        User currentUser = getCurrentUser();
        // 这里不需要验证所有权，因为即使用户已无权访问该笔记，他也应该能取消自己的收藏记录
        favoriteMapper.delete(currentUser.getId(), noteId);
    }

    // 获取当前用户的所有收藏笔记
    public List<Note> getMyFavorites() {
        User currentUser = getCurrentUser();
        return favoriteMapper.findFavoriteNotesByUserId(currentUser.getId());
    }

    // 辅助方法：获取当前登录的用户实体
    private User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userMapper.findByUsername(username);
    }
}
